const { sqlite3 } = require('../../mysql')

// 获取用户地址数据
async function getAddress(ctx) {
  console.log(ctx.query.openId)
  const openId = ctx.query.openId
  const addressData = await sqlite3('address').where({
    user_id: openId,
  })
  // console.log(addressData)
  if (addressData.length != 0) {
    ctx.body = {
      addressData: addressData[0],
      result: true,
    }
  } else {
    ctx.body = false
  }
}

// 保存更新用户地址数据
async function saveAddress(ctx) {
  console.log('获取ctx数据：', ctx.request.body)
  const { user_id, name, mobile, address, address_detail, is_default } =
    ctx.request.body.userInfo
  // const user_id = ctx.request.body.openId
  // const userInfo = ctx.request.body.userInfo

  console.log(user_id, name, mobile, address, address_detail, is_default)
  const searchAddress = await sqlite3('address')
    .where({
      user_id,
    })
    .select()
  if (searchAddress.length > 0) {
    console.log('更新用户地址数据')
    const data = await sqlite3('address')
    .where({
      user_id,
    })
    .update({
      user_id,
      name,
      mobile,
      address,
      address_detail,
      is_default,
    })
    ctx.body = {
      data: 'updata success',
    }
  } else {
    console.log('添加用户地址数据')
    const data = await sqlite3('address')
      .where({
        user_id,
      })
      .insert({
        user_id,
        name,
        mobile,
        address,
        address_detail,
        is_default,
      })
    ctx.body = {
      data: 'updata fail',
    }
  }
}

// 保存更新用户地址数据
// async function saveAddress(ctx) {
//   console.log('获取ctx数据：', ctx.request.body)
//   console.log('openId:', ctx.request.body.openId);
//   const { openId, userName, telNumber, address, addrDetail, checked } = ctx.request.body
//   const addressData = await sqlite3('address').where({
//     user_id: openId,
//   })
//   console.log('addressData:', addressData)
//   if (addressData.length == 0) {
//     const data = await sqlite3('address').insert({
//       name: userName,
//       user_id: openId,
//       mobile: telNumber,
//       address: address,
//       is_default: checked == 'true' || checked ? 1 : 0,
//       address_detail: addrDetail
//     })
//     // console.log(data)
//     ctx.body = {
//       data: 'insert'
//     }
//   } else {
//     console.log('wu');
//     const addressUpdata = await sqlite3('address').where({
//       'user_id': openId,
//     }).update({
//       name: userName,
//       user_id: openId,
//       mobile: telNumber,
//       address: address,
//       is_default: checked == 'true' || checked ? 1 : 0,
//       address_detail: addrDetail
//     })
//     ctx.body = {
//       data: 'update'
//     }
//   }
// }

module.exports = { getAddress, saveAddress }
